import AppConfig from '../config/appConfig';
import { UserAgent } from '../config/variable';
import { getSu, getSign, kvStringify } from './index';
const crypto = require('crypto-js');

export const getParams = (data?) => {
    let params: any = {
        // ref: r,
        _ref: '',
        _su: getSu(),
        token: global.userToken,//'e9c768e479134a78a9ae80fccf0e9b7a',//t.token || "",
        appversion: AppConfig.appVersion,
        client_type: AppConfig.clientType,
        revision: AppConfig.appVersion,
        oauth_md5:  global.userOpenId //'30659c87b229cf4e4902265de37559bd',//t.oauthMd5
        // userMd5: ''
    };

    if (data) {
        params.args = JSON.stringify(data);
    }

    params._sign = getSign(params);
    return params;
};

const encryptAes = (e, t) => {
    return crypto.AES.encrypt(e, crypto.enc.Utf8.parse(t), {
        mode: crypto.mode.ECB,
        padding: crypto.pad.Pkcs7
    }).ciphertext.toString(crypto.enc.Base64);
}

const encryptMd5 = (e, t) => {
    return crypto.HmacMD5(e, crypto.enc.Utf8.parse(t)).toString(crypto.enc.Base64);
};

function fnUuid() {
    var r = new Date().getTime();
    return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(e) {
        var a = (r + 16 * Math.random()) % 16 | 0;
        return r = Math.floor(r / 16), ("x" == e ? a : 3 & a | 8).toString(16);
    }) + '1.0.44';
}

function k(e) {
    for (var t, o = ['type', 'touchSupport', 'platform', 'pixelRatio', 'colorDepth', 'deviceMemory', 'sessionStorage', 'localStorage', 'indexedDB', 'openDatabase', 'plugins', 'userAgent', 'webdriver', 'batteryInfo', 'sign_timestamp'], u = "", s = 0, c = o.length; s < c; s++) {
        var f = e[o[s]];
        "boolean" == typeof f && !0 === f ? f = 1 : typeof f === 'boolean' && !1 === f && (f = 0), 
        u += "".concat(f, "|");
    }
    t = encryptMd5(u, '4wYBlMmBj!NY6a3ql#Tu3xoKf&va$P8P');
    return {fingerprintKey: u + t, finger: t};
}

const getCfg = () => {
    let cfgInfo: any = {};
    cfgInfo.type = 'WEB';
    cfgInfo.touchSupport = -1;
    cfgInfo.platform = 'macintel';
    cfgInfo.pixelRatio = 2;
    cfgInfo.colorDepth = 24,
    cfgInfo.deviceMemory = 8, 
    cfgInfo.sessionStorage = true, 
    cfgInfo.localStorage = true, 
    cfgInfo.indexedDB = true, 
    cfgInfo.openDatabase = -1, 
    cfgInfo.plugins = true, 
    cfgInfo.userAgent = 'Safari', 
    cfgInfo.webdriver = false, 
    cfgInfo.batteryInfo = new Promise(() => {});
    cfgInfo.sign_timestamp = fnUuid();

    return cfgInfo;
}

function C(e) {
    var r = 0 < arguments.length && void 0 !== e ? e : null;
    var bIsDebug;
    return e = [], r && (e = ['uba-'].filter(function(e) {
        return 0 <= r.indexOf(e);
    })), bIsDebug && !e.length;
}

function m(e) {
    var a = void 0 === (a = e.sType) ? "GET" : a, o = void 0 === (e.sHost, o = e.sUrl) ? null : o;
    e = void 0 === (e = e.sQuery) ? null : e, a = a.toLocaleUpperCase() + "?" + e, C(o) && console.log('<<signiointext>>>', a);
    // console.log(a);
    // a = 'GET?oauth_md5=30659c87b229cf4e4902265de37559bd&client_type=10&_ref=&token=&_sign=3aa30dd168f3b79910eba6d51388dcc0&revision=4464&appversion=4464&sign_timestamp=9b4d4e090d06451eb0d12a9494f0ab671.0.44&hmd5_finger=BxIcvLxH2aq3qkTiXSkJQA==&args={"phone_no":"18519203764"}&_su=24031600175596810000000644071103'
    // console.log(encryptMd5(a, '4wYBlMmBj!NY6a3ql#Tu3xoKf&va$P8P'))
    return encryptMd5(a, '4wYBlMmBj!NY6a3ql#Tu3xoKf&va$P8P');
}

export const getHeader = (url, method, contentType, params, cityId = 1017) => {
    const turingToken = "";
    const aesSecreKey = 'P8P$av&fKox3uT#lq3a6YN!jBmMlBYw4';

    const cfgInfo = getCfg();
    const { fingerprintKey, finger } = k(cfgInfo);
    // console.log('fingerprintKey', fingerprintKey)
    const u = encryptAes(fingerprintKey, aesSecreKey);
    // console.log(fingerprintKey)
    // console.log(u)
    const fingerprinting = u.includes(",") ? u.split(",")[0] : u;
    const h = contentType ? contentType : 'urlencoded';
    const oEncryptData = {
        oauth_md5: params.oauth_md5,
        client_type: `${params.client_type}`,
        _ref: params._ref,
        token: params.token,
        _sign: params._sign,
        revision: params.revision,
        appversion: `${params.appversion}`,
        sign_timestamp: cfgInfo.sign_timestamp,
        hmd5_finger: finger,
        args: params.args,
        _su: params._su
    };
    
    const s = m({
        sType: method,
        sUrl: url,//'https://qapi.huolala.cn/send_sms_code?_ref=&_su=24031601144820610000001862272187&token=&appversion=4464&oauth_md5=30659c87b229cf4e4902265de37559bd&client_type=10&revision=4464&args=%7B%22phone_no%22%3A%2218519203764%22%7D&_sign=feb219cf4b6fe52ab9c3dcb7ce5aeb09',
        sQuery: kvStringify(oEncryptData, method, h)
    });
    // console.log(s)
    const sign = s.includes(",") ? s.split(",")[0] : s;
    
    let header: any = {
        // "x-hll-appid": "com.huolala.".concat(w[u.default.clientType] || "mini", ".user"),
        "x-hll-appid": "com.huolala.weixin.user",
        "x-hll-city-id": cityId,//m || l,
        "x-hll-device-id": "",
        "x-hll-loc": "",//h.lon ? "".concat(h.lon, ",").concat(h.lat) : "",
        "x-hll-phone-md5": "",//f ? s : "",
        "x-hll-revision": AppConfig.appVersion,
        "x-hll-route-cityid": cityId,
        "x-hll-user-id": "",//f ? n : "", 
        "x-h5-sdkversion": 2000,
        "x-javascript-fingerprinting": fingerprinting,
        "x-sign-js": sign,
        'User-Agent': UserAgent
    };

    header["x-hll-appid-revision"] = header["x-hll-appid"] + "_" + header["x-hll-revision"];
    header["x-hll-route-cityid"] = header["x-hll-city-id"];
    header["x-hll-dt"] = turingToken || "DTUnknown";

    return header;
};